<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-tabs v-model="activeName" type="card" @tab-click="handTableClick">
        <el-tab-pane label="未生成" name="first"></el-tab-pane>
        <el-tab-pane label="已生成" name="second"></el-tab-pane>
        <el-tab-pane label="全部" name="all"></el-tab-pane>
      </el-tabs>

      <el-form-item label="主题名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入主题名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="大纲名称" prop="outlineName">
        <el-input
          v-model="queryParams.outlineName"
          placeholder="请输入大纲名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="生成时间" prop="updateTime">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['article:topicTitle:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['article:topicTitle:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:topicTitle:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="openImportTable">
          导入主题</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['article:topicTitle:export']"
        >导出</el-button>
      </el-col>


      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-promotion"
          size="mini"
          :disabled="multiple"
          @click="genTask"
          v-hasPermi="['article:topicTitle:remove']"
        >批量生成勾选文章</el-button>
      </el-col>


      <el-col :span="1.5">
        <el-dropdown icon="el-icon-refresh"  size="mini" split-button type="primary"  @click="genTaskAll">
          生成当前查询下所有
          <el-dropdown-menu slot="dropdown">
            <span style="margin-left: 10px">指定数量：</span>
            <el-input-number v-model="gennum" controls-position="right" @change="handleSelectChange" :min="0" :max="30000"></el-input-number>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>

    </el-row>



    <el-table v-loading="loading" :data="topicTitleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号"  width="80"  align="center" prop="id" />
      <el-table-column label="主题名称" width="350" align="center" prop="title" />
<!--      <el-table-column label="使用模型" width="100" align="center" prop="modelName" />-->
      <el-table-column prop="modelName" label="使用模型" width="150">
        <template slot-scope="scope">
          <dict-tag effect="dark" :options="dict.type.gpt_model" :value="scope.row.modelName"/>
        </template>
      </el-table-column>

      <el-table-column label="花费token" width="100" align="center" prop="useToken" />
      <el-table-column label="大纲名称" width="100" align="center" prop="outlineName" />
      <el-table-column label="所属类目" align="center" prop="className" />

<!--      <el-table-column label="状态" align="center" prop="status" />-->
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gen_status" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column label="使用语言" align="center" prop="language" />
      <el-table-column label="更新时间" align="center" width="200" prop="updateTime" />
      <el-table-column label="操作" align="center" fixed="right" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status==1"
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleview(scope.row)"
          >查看</el-button>

          <el-button
            v-if="scope.row.status==0"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            :loading="scope.row.genTaskLoading"
            @click="genTask(scope.row)"
          >生成</el-button>
          <el-button
            v-if="scope.row.status==1"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            :loading="scope.row.genTaskLoading"
            @click="genTask(scope.row)"
          >重新生成</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['article:topicTitle:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['article:topicTitle:remove']"
          >删除</el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改主题文章对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="主题名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入主题名称" />
        </el-form-item>
<!--        <el-form-item label="分类名称" prop="className">-->
<!--          <el-input v-model="form.className" placeholder="请输入分类名称" />-->
<!--        </el-form-item>-->

        <el-form-item label="类目" prop="className">
          <treeselect style="width: 140px" ref="optionClassRef"  @select="searchClassSelect" v-model="form.classId" :options="spiderClassOptions" :show-count="true" placeholder="请选择归属分类" />
        </el-form-item>

        <el-form-item label="大纲id"prop="outlineId">
          <el-input v-model="form.outlineId" placeholder="请输入大纲id" />
        </el-form-item>
        <el-form-item label="大纲名称" prop="outlineName">
          <el-input v-model="form.outlineName" placeholder="请输入大纲名称" />
        </el-form-item>
        <el-form-item label="需求提示词" prop="demandPrompts">
          <el-input v-model="form.demandPrompts" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="使用语言" prop="language">
          <el-input v-model="form.language" placeholder="请输入使用语言" />
        </el-form-item>
        <el-form-item label="文章内容Id" prop="contentId">
          <el-input v-model="form.contentId" placeholder="请输入文章内容Id" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 导入数据包 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="900px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx"
        :headers="upload.headers"
        :action="upload.url+ '?classId=' + form.classId +
        '&className='+form.className +
        '&prompts='+form.demandPrompts +
        '&outlineId='+form.outlineId +
        '&outlineName='+form.outlineName +
        '&language='+form.language "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="分类" prop="classId">
                    <treeselect style="width: 240px" ref="optionClassRef"  @select="addSelect" v-model="form.classId" :options="spiderClassOptions" :show-count="true" placeholder="请选择归属分类" />
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item label="生成要求">
                     <el-input v-model="form.demandPrompts" type="textarea" placeholder="请输入内容" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="使用大纲">
                    <el-select v-model="form.outlineId" @change="promptsChange($event)"  ref="optionOutlineRef"  placeholder="请选择使用大纲">
                      <el-option
                        v-for="item in outlinesOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="语言">
                      <el-select
                        v-model="form.language"
                        placeholder="使用语言"
                        clearable
                        style="width: 240px"
                      >
                        <el-option
                          v-for="dict in dict.type.language"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                  </el-form-item>
                </el-col>
<!--                outlineId:null,-->
<!--                outlineName:null,-->
<!--                language:null,-->


              </el-row>
            </el-form>

          </div>
          <span>仅允许导入xls格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载包模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listTopicTitle, getTopicTitle, delTopicTitle, addTopicTitle, updateTopicTitle,spiderClassSelect,outlinesSelect,startGen,startGenAll } from "@/api/article/topicTitle";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "TopicTitle",
  components: { Treeselect },
  dicts: ['language','gen_status','gpt_model'],
  //
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      selectGen:[],
      // 时间范围
      daterangeCreateTime: [],
      // 显示搜索条件
      showSearch: true,
      //tab选项
      activeName: 'first',
      outlinesOptions:[],
      spiderClassOptions:[],
      useModel:'gpt-3.5-turbo-16k',
      // 总条数
      total: 0,
      gennum:0,
      // 主题文章表格数据
      topicTitleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "上传数据包",

        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // updateSupport: 0,
        classId: null,
        className:null,
        demandPrompts:null,
        outlineId:null,
        outlineName:null,
        language:null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/article/topicTitle/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        className: null,
        gennum:0,
        outlineName: null,
        status: 0,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询主题文章列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }

      listTopicTitle(this.queryParams).then(response => {
        this.topicTitleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        classId: null,
        className: null,
        outlineId: null,
        outlineName: null,
        demandPrompts: null,
        useModel:'gpt-3.5-turbo-16k',
        status: null,
        language: null,
        createBy: null,
        gennum:null,
        contentId: null
      };
      this.resetForm("form");
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      // this.$refs.import.show();
      // alert();
      spiderClassSelect().then(response => {
        this.spiderClassOptions = response.data;
      });
      outlinesSelect().then(response => {
        this.outlinesOptions = response.rows;
      });
      // /** 查询生成模型下拉框列表 */
      // PromptsSelect().then(response => {
      //   this.promptsOptions = response.data;
      // });
      this.reset();
      this.upload.title = "主题名称上传";
      this.upload.open = true;
    },
    handleSelectChange(value){
      console.log(value);
      this.gennum = value;
    },
    handleview(row){
      const contentId = row.contentId || 0;
      this.$router.push('/article/viewArt/index/' + contentId+'/topic')
    },
    promptsChange(value){
      var obj = {};
      //使用find()方法在下拉数据中根据value绑定的数据查找对象。
      obj = this.outlinesOptions.find(function(item){
        console.log(item)
        return item.id === value;
      });
      this.form.outlineName = obj.name;
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.download('system/user/importTemplate', {
      // }, `user_template_${new Date().getTime()}.xlsx`)
      this.$download.zip("/common/download?fileName=temp.xlsx&delete=false" , "temp.xlsx");

    },
    //分类选择框
    addSelect(value){
      this.form.className = value.label;
      console.log(this.className)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.daterangeCreateTime = [];
    },
    searchClassSelect(value){
      this.queryParams.className = value.label;
      this.queryParams.classId = value.id;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加主题文章";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTopicTitle(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改主题文章";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTopicTitle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTopicTitle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handTableClick(tab, event) {
      switch (tab.name) {
        case "first":
          this.queryParams.status = '0';
          break;
        case "second":
          this.queryParams.status = '1';
          break;
        case "all":
          this.queryParams.status = null;
          break;
      }
      this.getList();
    },
    //执行生成
    genTask(row){
      const ids = row.id || this.ids;
      this.$set(row, 'genTaskLoading', true);
      this.$modal.confirm('是否确认生成主题文章编号为"' + ids + '"的数据项？').then(function() {
        return startGen(ids);
      }).then(() => {
        this.activeName= 'all';
        this.getList();
        this.$set(row, 'genTaskLoading', false);
        this.$modal.msgSuccess("任务提交成功");
      }).catch(() => {
        this.$set(row, 'genTaskLoading', false);
      });
    },
    genTaskAll(){
      // startGenAll
      console.log(typeof this.queryParams);
      let genps = this.queryParams;
      console.log(genps)
      genps.gennum = this.gennum;
      genps.status = genps.status==null?"0":genps.status.toString();
      console.log(genps)
      this.$modal.confirm('确定执行任务吗？').then(function() {
        return startGenAll(genps);
      }).then(() => {
        this.$modal.msgSuccess("任务提交成功");
        this.activeName= 'all';
        this.queryParams.status = null;
        this.getList();
      }).catch(() => {
      });



    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除主题文章编号为"' + ids + '"的数据项？').then(function() {
        return delTopicTitle(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('article/topicTitle/export', {
        ...this.queryParams
      }, `topicTitle_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
